/**
 * 
 */
package com.foreveross.bsl.mam.app.application.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.inject.Named;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONException;
import org.json.JSONObject;

import com.foreveross.bsl.common.utils.bean.BeanHelper;
import com.foreveross.bsl.common.utils.bean.Constants;
import com.foreveross.bsl.mam.app.application.AppMainApplication;
import com.foreveross.bsl.mam.app.application.AppPackageMetaInfoApplication;
import com.foreveross.bsl.mam.app.application.AppSecretApplication;
import com.foreveross.bsl.mam.app.application.AppVersionApplication;
import com.foreveross.bsl.mam.app.application.AppVersionWidgetVersionApplication;
import com.foreveross.bsl.mam.app.application.DefindApplication;
import com.foreveross.bsl.mam.app.application.vo.AndroidPackageMetaInfoVo;
import com.foreveross.bsl.mam.app.application.vo.AppMainVo;
import com.foreveross.bsl.mam.app.application.vo.AppSecretVo;
import com.foreveross.bsl.mam.app.application.vo.AppVersionVo;
import com.foreveross.bsl.mam.app.application.vo.AppVersionWidgetVersionVo;
import com.foreveross.bsl.mam.app.application.vo.DefindVo;
import com.foreveross.bsl.mam.app.application.vo.ModuleInfoVo;
import com.foreveross.bsl.mam.app.application.vo.MamPackageRequestVo;
import com.foreveross.bsl.mam.app.application.vo.PackageResultVo;
import com.foreveross.bsl.mam.app.application.vo.PackageTaskVo;
import com.foreveross.bsl.mam.model.app.domain.PackageTask;
import com.foreveross.bsl.mam.model.application.AttachmentApplication;
import com.foreveross.bsl.mam.model.application.WidgetApplication;
import com.foreveross.bsl.mam.model.application.WidgetCategoryApplication;
import com.foreveross.bsl.mam.model.application.WidgetVersionApplication;
import com.foreveross.bsl.mam.model.application.vo.AttachmentVO;
import com.foreveross.bsl.mam.model.application.vo.WidgetCategoryVO;
import com.foreveross.bsl.mam.model.application.vo.WidgetVO;
import com.foreveross.bsl.mam.model.application.vo.WidgetVersionVO;

@Named("appPkgMetaInfoApplication")
public class AppPackageMetaInfoApplicationImpl implements
		AppPackageMetaInfoApplication {

	private Log log = LogFactory
			.getLog(AppPackageMetaInfoApplicationImpl.class);

	@Inject
	private AppVersionApplication appVersionApplication;

	@Inject
	private DefindApplication defindApplication;
	@Inject
	private AppSecretApplication appSecretApplication;

	@Inject
	private AppMainApplication appMainApplication;

	@Inject
	private AppVersionWidgetVersionApplication appVersionWidgetVersionApplication;

	@Inject
	private WidgetVersionApplication widgetVersionApplication;

	@Inject
	private AttachmentApplication attachmentApplication;

	@Inject
	private WidgetApplication widgetApplication;

	@Inject
	private WidgetCategoryApplication widgetCategoryApplication;

	/**
	 * [一句话功能简述]<BR>
	 * [功能详细描述]
	 * 
	 * @param packageRequestVo
	 * @return 2013-7-3 下午5:19:41
	 */
	@Override
	public AndroidPackageMetaInfoVo getPackageInfoByOS(
			MamPackageRequestVo packageRequestVo) {
		AndroidPackageMetaInfoVo abstractPackageMetaInfoVo = null;
		AppMainVo app = appMainApplication.getEntitybyIdentify(packageRequestVo
				.getAppId());
		if (app != null) {
			if (packageRequestVo.getOS() == Constants.ANDROID) {
				AppVersionVo appVersion = appVersionApplication.findByVersion(
						"android", app.getId(), packageRequestVo.getVersion());
				if (appVersion == null) {
					appVersion = new AppVersionVo();
					appVersion.setPlatformid("android");
					appVersion.setApplicationid(app.getId());
					appVersion.setVersion(packageRequestVo.getVersion());
					appVersion.setBuild(packageRequestVo.getVersionCode());
					appVersion.setRelease_note(packageRequestVo.getDesc());
				}
				try {
					abstractPackageMetaInfoVo = packAndroid(appVersion);
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		}
		return abstractPackageMetaInfoVo;
	}

	/**
	 * 此方法描述的是：android打包业务逻辑处理
	 * 
	 * @author: panhm@foreveross.com
	 * @version: 2013-7-23 上午10:26:34
	 * @throws JSONException
	 */

	private AndroidPackageMetaInfoVo packAndroid(AppVersionVo versioinVo)
			throws JSONException {
		AppMainVo appMain = appMainApplication.getEntity(versioinVo
				.getApplicationid());
		DefindVo defindPng = defindApplication.getEntityByAppId(
				versioinVo.getPlatformid(), versioinVo.getVersion(),
				versioinVo.getApplicationid());
		/* 组装android 打包对象信息 */
		AndroidPackageMetaInfoVo androidPackageMetaInfoVo = new AndroidPackageMetaInfoVo();
		androidPackageMetaInfoVo.setAppCategory(appMain.getAppCategoryVo()
				.getName());
		androidPackageMetaInfoVo.setAppId(versioinVo.getApplicationid());
		androidPackageMetaInfoVo
				.setAppVersionDesc(versioinVo.getRelease_note());
		androidPackageMetaInfoVo.setAppName(appMain.getApp_name());
		androidPackageMetaInfoVo.setAppVersion(versioinVo.getVersion());
		androidPackageMetaInfoVo.setAppIntro(appMain.getDiscription());
		androidPackageMetaInfoVo.setAppVersionCode(versioinVo.getBuild());
		androidPackageMetaInfoVo.setOS(Constants.ANDROID);
		if (defindPng != null) {
			/* 设置android logo */
			String iconsLogo = defindPng.getIcons();
			if (StringUtils.isNotEmpty(iconsLogo)) {
				JSONObject json = new JSONObject(iconsLogo);
				if (!json.isNull("logo-xdpi")) {
					androidPackageMetaInfoVo.setLogo_xdpi_id(json
							.getString("logo-xdpi"));
				}
				if (!json.isNull("logo-hdpi")) {
					androidPackageMetaInfoVo.setLogo_hdpi_id(json
							.getString("logo-hdpi"));
				}
				if (!json.isNull("logo-mdpi")) {
					androidPackageMetaInfoVo.setLogo_mdpi_id(json
							.getString("logo-mdpi"));
				}
				if (!json.isNull("logo-ldpi")) {
					androidPackageMetaInfoVo.setLogo_ldpi_id(json
							.getString("logo-ldpi"));
				}
			}
			/* 设置android 启动页 */
			String defaultImgs = defindPng.getDefaultImgs();
			if (StringUtils.isNotEmpty(defaultImgs)) {
				JSONObject json = new JSONObject(defaultImgs);

				if (!json.isNull("default-xdpi")) {
					androidPackageMetaInfoVo.setSplash_xdpi_id(json
							.getString("default-xdpi"));
				}
				if (!json.isNull("default-hdpi")) {
					androidPackageMetaInfoVo.setSplash_hdpi_id(json
							.getString("default-hdpi"));
				}
				if (!json.isNull("default-mdpi")) {
					androidPackageMetaInfoVo.setSplash_mdpi_id(json
							.getString("default-mdpi"));

				}
				if (!json.isNull("default-ldpi")) {
					androidPackageMetaInfoVo.setSplash_ldpi_id(json
							.getString("default-ldpi"));
				}
			}

		}
		/* 获取证书密钥 */
		AppSecretVo secretVo = appSecretApplication.findByAppId(
				versioinVo.getApplicationid(), versioinVo.getPlatformid());
		if (secretVo != null) {
			if (StringUtils.isNotEmpty(secretVo.getCertid())) {
				androidPackageMetaInfoVo.setCertification_id(secretVo
						.getCertid());
				androidPackageMetaInfoVo.setKeyAlias(secretVo.getKeyAlias());
				androidPackageMetaInfoVo.setKeyPass(secretVo.getCertkey());
				androidPackageMetaInfoVo.setStorePass(secretVo.getStorePass());
			}
		}
		// 查询关联模块，listResult
		List<AppVersionWidgetVersionVo> listResult = appVersionWidgetVersionApplication
				.getListByPlatEntity(versioinVo.getPlatformid(),
						versioinVo.getVersion(), versioinVo.getApplicationid());
		if (listResult != null) {
			List<ModuleInfoVo> pkgModules = new ArrayList<ModuleInfoVo>();
			for (AppVersionWidgetVersionVo appWidget : listResult) {
				WidgetVersionVO widgetVersionVO = widgetVersionApplication
						.widgetVersion(appWidget.getWidgetId(),
								appWidget.getWidgetVersion());
				if (widgetVersionVO != null) {
					WidgetVO widgetV0 = widgetApplication
							.getEntity(widgetVersionVO.getWidget_id());
					if (widgetV0 != null) {
						WidgetCategoryVO category = widgetCategoryApplication
								.getEntity(widgetV0.getCategory_id());
						if (category != null) {
							ModuleInfoVo moduleInfoVo = new ModuleInfoVo();
							moduleInfoVo.setBuild(widgetVersionVO.getBuild());
							moduleInfoVo.setCategory(category.getName());
							moduleInfoVo.setName(widgetV0.getName());
							moduleInfoVo.setVersion(widgetVersionVO
									.getVersion());
							moduleInfoVo.setIcon(widgetV0.getIcon_id());
							moduleInfoVo.setDownloadUrl(widgetVersionVO
									.getBoundle());
							moduleInfoVo.setIdentifier(widgetV0.getIdentify());
							moduleInfoVo.setReleaseNote(widgetVersionVO
									.getRelease_not());
							moduleInfoVo.setHidden(widgetV0.isHidden());
							pkgModules.add(moduleInfoVo);
						}
					}

				}
			}
			androidPackageMetaInfoVo.setPkgModules(pkgModules);
		}

		return androidPackageMetaInfoVo;
	}

	@Override
	public void callBackResult(final PackageResultVo packageResultVo) {
		log.info("[callBackResult][packageResultVo]"
				+ packageResultVo.toString());
		// 异步线程处理打包结果

		// 获取缓存数据
		String task_id = packageResultVo.getPackageSeq();
		PackageTaskVo taskVo = this.getEntity(task_id);
		if (packageResultVo.isSuccess()) {
			taskVo.setStatus(3);
			taskVo.setMsg(packageResultVo.getReason());
			taskVo.setFinishTime(new Date());

			String bundle = packageResultVo.getFileDistPath();
			AppMainVo appMain = appMainApplication.getEntity(taskVo.getAppId());
			Date date = new Date();
			AttachmentVO attachment = new AttachmentVO();
			attachment.setAvailable(1);
			attachment.setLocalFilename(bundle);
			attachment.setContentType("application/octet-stream");
			attachment.setUploadFilename(appMain.getIdentifier() + ".apk");
			attachment.setCreatedAt(date);
			attachment.setModifiedAt(date);
			attachment.setId(bundle);
			AttachmentVO att = attachmentApplication.saveEntity(attachment);
			log.info("[通知打包结果]update success");
			taskVo.setPackageUrl(att.getId());
		} else {
			taskVo.setStatus(0);
			taskVo.setMsg(packageResultVo.getErrorMsg());
			taskVo.setFinishTime(new Date());
		}
		this.updateEntity(taskVo);// 更新数据库.

	}

	@Override
	public PackageTaskVo saveEntity(PackageTaskVo entity) {
		// TODO Auto-generated method stub
		PackageTask task = new PackageTask();
		BeanHelper.copyProperties(task, entity);
		PackageTask result = (PackageTask) task.save();
		BeanHelper.copyProperties(entity, result);
		return entity;
	}

	@Override
	public PackageTaskVo updateEntity(PackageTaskVo entity) {
		// TODO Auto-generated method stub
		PackageTask task = new PackageTask();
		BeanHelper.copyProperties(task, entity);
		PackageTask result = (PackageTask) task.save();
		BeanHelper.copyProperties(entity, result);
		return entity;
	}

	@Override
	public void deleteEntity(String id) {
		// TODO Auto-generated method stub
		PackageTask task = new PackageTask();
		task.delete(id);
	}

	@Override
	public PackageTaskVo getEntity(String id) {
		// TODO Auto-generated method stub
		PackageTask task = new PackageTask();
		PackageTask result = (PackageTask) task.findOne(id);
		if (result != null) {
			PackageTaskVo entity = new PackageTaskVo();
			BeanHelper.copyProperties(entity, result);
			return entity;
		}
		return null;

	}
}
